package be.vdabantwerpen.gow.servlets;

import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import be.vdabantwerpen.gow.dao.PostDAO;
import be.vdabantwerpen.gow.entities.GOWUser;
import be.vdabantwerpen.gow.entities.Post;
import be.vdabantwerpen.gow.entities.Reply;
import be.vdabantwerpen.gow.services.PostService;
import be.vdabantwerpen.gow.services.PostServiceImpl;
import com.google.appengine.repackaged.org.joda.time.DateTime;

/**
 * Servlet implementation class ReplyPost
 */
public class ReplyPostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String VIEW = "/WEB-INF/JSP/posts/replypost.jsp";
	private static final String REDIRECT_URL = "/reply";
        private static final PostService postService = new PostServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
            int postId = 0;
            String postIdAsString = request.getParameter("postId");
            if(postIdAsString != null && !postIdAsString.isEmpty()){
                postId = Integer.parseInt(postIdAsString);
            }
            else {
                response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/posts"));;
            }
            Post post = postService.read(postId);
            HttpSession session = request.getSession();
            GOWUser user = null;
            if(session != null){
                user = (GOWUser)session.getAttribute("user");
            }
            String userName = null;
            if(user != null){
                userName = user.getUserName();
            }
            Reply reply = new Reply(post, userName, DateTime.now(), "");
            request.setAttribute("post", post);
            request.setAttribute("postReply", reply);
            RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
            dispatcher.forward(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
            
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + REDIRECT_URL));
            }

	}
